/*-----------------------------------------------------------------------------
	The contents of this file are subject to the Mozilla Public License
	Version 1.1 (the "License"); you may not use this file except in
	compliance with the License.You may obtain a copy of the License at
	http://www.mozilla.org/MPL/MPL-1.1.html
	
	Software distributed under the License is distributed on an "AS IS"
	basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
	License for the specific language governing rights and limitations
	under the License.
	
	The Original Code is Fever Framework code.
	
	The Initial Developer of the Original Code is Romain Ecarnot.
	Portions created by Initial Developer are Copyright (C) 2006
	the Initial Developer. All Rights Reserved.
	
	Contributor(s):
	
	Unless required by applicable law or agreed to in writing, software
	distributed under the License is distributed on an "AS IS" BASIS,
	WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
	See the License for the specific language governing permissions and
	limitations under the License.
-----------------------------------------------------------------------------*/

import fever.app.browser.history.HistoryStatus;
import fever.app.browser.history.strategy.AbstractHistoryStrategy;
import fever.commands.JSCommand;
import fever.commands.JSMethodName;
import fever.Fever;

import flash.external.ExternalInterface;

/**
 * Browser history managment using <strong>dhtmlHistory</strong> 
 * Javascript engine.
 * 
 * @author Romain Ecarnot
 */
class fever.app.browser.history.strategy.DHTMLHistoryStrategy extends AbstractHistoryStrategy
{
	//-------------------------------------------------------------------------
	// Private properties
	//-------------------------------------------------------------------------
	
	private static var _instance : DHTMLHistoryStrategy;
	
	private static var GET_STATE : JSMethodName = new JSMethodName( 'getHistoryState' );
	private static var SET_STATE : JSMethodName = new JSMethodName( 'setHistoryState' );
	
	private var _connected : Boolean;
	 
	private var _setCommand : JSCommand;
	private var _getCommand : JSCommand;
	
	
	//-------------------------------------------------------------------------
	// Public Properties
	//-------------------------------------------------------------------------
	
	/** SWF ID in html page. */
	public static var SWF_ID : String = 'fswf';
		
	
	//-------------------------------------------------------------------------
	// Public API
	//-------------------------------------------------------------------------
	
	/**
	 * Returns {@link DHTMLHistoryStrategy} unique instance.
	 * 
	 * <p>Singleton pattern.
	 */
	public static function getInstance() : DHTMLHistoryStrategy
	{
		if( !_instance ) _instance = new DHTMLHistoryStrategy();
		return _instance;
	}
	
		
	//-------------------------------------------------------------------------
	// Private implementation
	//-------------------------------------------------------------------------
	
	/**
	 * Constructor.
	 */
	private function DHTMLHistoryStrategy ( )
	{		
		super();
	}
	
	private function _parse( o : Object ) : HistoryStatus
	{
		return new HistoryStatus( o.location, o.data );
	}
	
	private function _init() : Void
	{
		var f : String = "";
		f += "function updateBrowser( nc, oData )";
		f += "{";
		f += "	if ( oData != null )";
		f += "	{";
		f += "		document.title = oData.title;";
		f += "		data = oData.data;";
		f += "	}";
		f += "}";
		ExternalInterface.call( "eval", f );
		
		f = "function _getSWFMovie( swfID )"; 
		f += "{";
		f += "if ( navigator.appName.indexOf(\"Microsoft\") != -1 ) return window[swfID];";
		f += "else return document[swfID];";
		f += "}";
		ExternalInterface.call( "eval", f );
		
		f = "function _sendStatus()";
		f += "{";
		f += "if( _getSWFMovie(\"" + SWF_ID + "\").restoreHistoryState )";
		f += "_getSWFMovie(\"" + SWF_ID + "\").restoreHistoryState( getHistoryState() );"; 
		f += "else return false;";
		f += "}";
		ExternalInterface.call( "eval", f );
		
		f = "function onHistoryChange( loc, oData )";
		f += "{";
		f += "updateBrowser( loc, oData );";
		f += "_sendStatus();";
		f += "}";
		ExternalInterface.call( "eval", f );
		
		f = "( loc, msg, oData )";
		f += "{	";
		f += "var data = { location : loc, title : msg, data : oData  };";
		f += "updateBrowser( loc, data );";
		f += "dhtmlHistory.add( loc, data);";
		f += "}";
		_setCommand = new JSCommand( SET_STATE, f );
		
		f = "()";
		f += "{";
		f += "	var loc = dhtmlHistory.getCurrentLocation();";
		f += "	if( historyStorage.hasKey( loc ) ) return historyStorage.get( loc );";
		f += "	else return { location : loc, title : null, data : null  };";
		f += "}";
		_getCommand = new JSCommand( GET_STATE, f );
		
		f = "function initHistory()";
		f += "{";
		f += "	dhtmlHistory.initialize();";	
		f += "	dhtmlHistory.addListener( onHistoryChange );";
		f += "	updateBrowser( dhtmlHistory.getCurrentLocation(), null );";
		f += "	return true;";
		f += "}";
		
		var pending : Object = ExternalInterface.call( 'eval', f );
		pending = ExternalInterface.call( 'initHistory' );
		
		 _connected = Boolean( ExternalInterface.addCallback( 'restoreHistoryState', this, _onUpdate ) );
	}
	
	private function _register( data : Object ) : Void 
	{
		_setCommand.call( _buildCorrectLink( _sLink ), Fever.application.getTitle(), data );
	}
	
    private function _getState() : HistoryStatus
	{
		return _parse( _getCommand.call() );
	}
	
	private function _onUpdate( data : Object ) : Void
	{
		var status : HistoryStatus = _parse( data );
		
		if( status.isAvailable() )
		{
			_process( status.state );
			_fireEvent( status );
		}
		else
		{
			_process( '' );	
		}
	}
}